package com.welab.pandahelper.http;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpHelper {

    private static OkHttpHelper mOkHttpHelper;
    private static OkHttpClient mOkHttpClient;

    private static Gson mGson;
    private Handler mHandler;

    private OkHttpHelper() {
        mOkHttpClient = new OkHttpClient();
        mGson = new Gson();

        //每发现一条消息就推送到Handler
        mHandler = new Handler(Looper.getMainLooper());
    }

    public static OkHttpHelper getOkHttpHelperInstance() {
        if (mOkHttpHelper == null) {
            synchronized (OkHttpHelper.class) {
                if (mOkHttpHelper == null) {
                    mOkHttpHelper = new OkHttpHelper();
                }
            }
        }
        return mOkHttpHelper;
    }

    //来区别请求的类型
    enum HttpMethodType {
        GET, POST
    }

    /**
     * 对外调用的Get，Post请求
     */
    public void get(String url, IBaseCallBack callBack) {
        Request request = buildRequest(
                url,
                null,
                HttpMethodType.GET);

        doRequest(request, callBack);
    }


    public Response get(String url) throws IOException {
        Request request = buildRequest(
                url,
                null,
                HttpMethodType.GET);

        Response execute = mOkHttpClient.newCall(request).execute();
        return execute;
    }



    public void post(String url, Map<String, String> parameter,
                     IBaseCallBack callBack) {

        Request request = buildRequest(
                url,
                parameter,
                HttpMethodType.POST);

        doRequest(request, callBack);
    }

    /**
     * 构建Get或Post请求的Request
     *
     * @param url        Url地址
     * @param parameter  Post请求所需要的参数
     * @param methodType 通过枚举来判断是Get还是Post
     * @return Request
     */
    private Request buildRequest(String url,
                                 Map<String, String> parameter,
                                 HttpMethodType methodType) {

        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (methodType == HttpMethodType.GET) {
            builder.get();
        } else {
            //构建参数获取
            RequestBody body = buildFormData(parameter);
            builder.post(body);
        }
        return builder.build();
    }

    /**
     * 构建Post请求的body
     */
    private RequestBody buildFormData(Map<String, String> parameter) {
        FormBody.Builder body = new FormBody.Builder();

        if (null != parameter) {

            for (Map.Entry<String, String> entry : parameter.entrySet()) {

                body.add(entry.getKey(), entry.getValue());
            }
        }
        return body.build();
    }


    /**
     * 通过构建好的Get或Post请求的Request，做网络访问
     */
    private void doRequest(final Request request, final IBaseCallBack callBack) {

//        callBack.onRequestBefore();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requestFailure(callBack, call, e);
            }

            @Override
            public void onResponse(Call call, Response response)
                    throws IOException {

                if (response.isSuccessful()) {
                    String resultStr = response.body().string();

                    if (callBack.mType == String.class) {

                        requestSuccess(callBack, response, resultStr);

                    } else {

                        try {
                            //防止Json解析错误
                            Object obj = mGson.fromJson(resultStr, callBack.mType);
                            requestSuccess(callBack, response, obj);

                        } catch (JsonParseException e) {
                            requestFailure(callBack, call, e);
                        }
                    }
                } else {
                    requestFailure(callBack, call, null);
                }
            }
        });
    }

    private void requestFailure(final IBaseCallBack callBack,
                                final Call call,
                                final Exception e) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callBack.onFailure(call, e);
            }
        });
    }

    private void requestSuccess(final IBaseCallBack callBack,
                                final Response response,
                                final Object o) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                callBack.onSuccess(response, o);
            }
        });
    }
}